import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { useSetState } from 'ahooks';
import { Button, Form, Input, message, Select, Tabs } from 'antd';
import { connect } from 'dva';
import React, { useMemo } from 'react';
const FormItem = Form.Item;
const FormList = Form.List;

const dataTypeEnum = [
  {
    label: 'Array',
    value: 'Array',
  },
  {
    label: 'Double',
    value: 'Double',
  },
  {
    label: 'Enumeration',
    value: 'Enumeration',
  },
  {
    label: 'String',
    value: 'String',
  },
  {
    label: 'Integer',
    value: 'Integer',
  },
  {
    label: 'Struct',
    value: 'Struct',
  },
];
interface State {
  loading: boolean;
}
const addServer: React.FC = (props: any) => {
  const { dispatch } = props;
  const [form] = Form.useForm();
  const type = Form.useWatch('type', form);
  const { history } = props;

  const [state, setState] = useSetState<State>({
    loading: false,
  });
  const formItemLayout = {
    labelCol: {
      style: { width: 200 },
    },
    wrapperCol: {
      span: 12,
    },
  };
  const onFinish = values => {
    const category = Object.assign(
      { array: null, struct: null, enumValue: null, douStrInt: null },
      values.category,
    );
    values.category = category;
    setState({ loading: true });
    dispatch({
      type: 'severDataType/postObjWithRes',
      payload: {
        url: '/api/ms-soa-service/v1/service/library/type/manage',
        ...values,
      },
      callback: res => {
        if (res.statusCode === '0') {
          message.success('添加成功');
          history.push('/soaManage/serviceManage/serviceLibrary?tab=1');
        }
      },
    }).finally(() => setState({ loading: false }));
  };

  const categoryDetailDom = useMemo(() => {
    const basicDataType = ['Double', 'String', 'Integer'];
    let comDom = <></>;
    if (type === 'Array') {
      comDom = (
        <FormItem {...formItemLayout} label={'数组元素参考数据类型'} name={['category', 'array']}>
          <Input placeholder={'请输入'} maxLength={50} />
        </FormItem>
      );
    } else if (type === 'Enumeration') {
      comDom = (
        <FormItem {...formItemLayout} label={'枚举值'} name={['category', 'enumValue']}>
          <Input placeholder={'请输入'} maxLength={50} />
        </FormItem>
      );
    } else if (basicDataType.includes(type)) {
      comDom = (
        <FormItem {...formItemLayout} label={'基础数据类型'} name={['category', 'douStrInt']}>
          <Input placeholder={'请输入'} maxLength={50} />
        </FormItem>
      );
    } else if (type === 'Struct') {
      comDom = (
        <FormList name={['category', 'struct']}>
          {(fields, { add, remove }) => {
            const items = fields.map((field, index) => ({
              label: index,
              key: field.key + '',
              children: (
                <>
                  <h3 style={{ display: 'flex' }}>
                    <div>结构体信息</div>
                    {fields.length > 1 ? (
                      <Button
                        style={{ marginLeft: 20 }}
                        type="primary"
                        onClick={() => remove(field.name)}
                      >
                        删除结构体成员
                      </Button>
                    ) : null}
                  </h3>
                  <FormItem {...formItemLayout} label={'结构体成员名称'} name={[field.name, 'name']}>
                    <Input placeholder={'请输入'} maxLength={50} />
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label={'结构体参考数据类型'}
                    name={[field.name, 'structReference']}
                  >
                    <Select
                      placeholder={'请选择'}
                      options={[
                        { label: 'IN', value: 'IN' },
                        { label: 'OUT', value: 'OUT' },
                      ]}
                    />
                  </FormItem>
                </>
              ),
            }));
            return (
              <>
                <h3 style={{ display: 'flex' }}>
                  <div>结构成员位置</div>
                  <Button style={{ marginLeft: 20 }} type="primary" onClick={() => add({})}>
                    添加结构体成员
                  </Button>
                </h3>
                <Tabs type="card" items={items} />
              </>
            );
          }}
        </FormList>
      );
    }

    return type ? (
      <>
        <FormItem {...formItemLayout} label={'备注'} name={['remark']}>
          <Input.TextArea maxLength={50} />
        </FormItem>
        {/* <FormItem noStyle name={'category'}> */}
        {comDom}
        {/* </FormItem> */}
      </>
    ) : null;
  }, [type]);
  return (
    <Form
      form={form}
      {...formItemLayout}
      initialValues={{
        category: {},
      }}
      onFinish={onFinish}
    >
      <h3>基本信息</h3>
      <FormItem
        label="数据类型名称"
        name="name"
        rules={[
          {
            required: true,
            whitespace: true,
            message: '请输入数据类型名称',
          },
        ]}
      >
        <Input placeholder="请输入数据类型名称" maxLength={50} />
      </FormItem>
      <FormItem
        label="数据类型描述"
        name="desc"
        rules={[
          {
            required: false,
          },
        ]}
      >
        <Input placeholder="请输入数据类型描述" maxLength={50} />
      </FormItem>
      <FormItem
        label="数据类型命名空间"
        name="nameSpace"
        rules={[
          {
            required: false,
            message: '请输入数据类型命名空间',
          },
        ]}
      >
        <Input placeholder="请输入数据类型命名空间" maxLength={50} />
      </FormItem>
      <FormItem
        label="数据类型类别"
        name="type"
        rules={[
          {
            whitespace: true,
            message: '请输入数据类型类别',
          },
        ]}
      >
        <Select
          onChange={v => {
            form?.resetFields(['category']);
            if (v === 'Struct') {
              form?.setFieldsValue({
                category: {
                  struct: [{}],
                },
              });
            }
          }}
          options={dataTypeEnum}
          placeholder="请选择数据类型类别"
        />
      </FormItem>
      {categoryDetailDom}
      <FormItem wrapperCol={{ style: { alignItems: 'center', margin: 20 }, span: 24 }}>
        <Button
          type="ghost"
          onClick={() => {
            history.push('/soaManage/serviceManage/serviceLibrary?tab=1');
          }}
        >
          取消
        </Button>
        <Button
          style={{ marginLeft: 20 }}
          type="primary"
          htmlType="submit"
          onClick={() => {
            console.log('🚀 ~ form?.getFieldsValue():', form?.getFieldsValue());
          }}
        >
          保存
        </Button>
      </FormItem>
    </Form>
  );
};
export default connect(state => state)(addServer);
